package com.wxzz.elearing.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wxzz.elearing.user.amqp.producer.UserMessageProducer;
import com.wxzz.elearing.user.dto.EnterpriseApplyDto;
import com.wxzz.elearing.user.dto.EnterpriseInsDto;
import com.wxzz.elearing.user.dto.FailEnterpriseApplyDto;
import com.wxzz.elearing.user.dto.PassEnterpriseApplyDto;
import com.wxzz.elearing.user.entity.*;
import com.wxzz.elearing.user.mapper.CommonCategoryMapper;
import com.wxzz.elearing.user.mapper.EnterpriseApplyMapper;
import com.wxzz.elearing.user.mapper.EnterpriseMapper;
import com.wxzz.elearing.user.mapper.WxUserMapper;
import com.wxzz.elearing.user.service.IEnterpriseApplyService;
import com.wxzz.elearing.user.service.IEnterpriseService;
import com.wxzz.elearing.user.service.openfeign.IEvaluationApiFeign;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class EnterpriseApplyImpl extends ServiceImpl<EnterpriseApplyMapper, EnterpriseApply> implements IEnterpriseApplyService {

    @Autowired
    private EnterpriseApplyMapper enterpriseApplyMapper;

    @Idempotent
    @Override
    public ReturnVO saveEnterpriseApply(EnterpriseApply enterpriseApply) {
        Integer count = enterpriseApplyMapper.selectCount(new LambdaQueryWrapper<EnterpriseApply>()
                .eq(EnterpriseApply::getWxUserId, enterpriseApply.getWxUserId())
                //不等于未通过时不能再次提交
                .ne(EnterpriseApply::getStatus, 2));
        if (count > 0) {
            throw new ServiceException("已提交过申请");
        }
        Integer phoneCount = enterpriseApplyMapper.selectCount(new LambdaQueryWrapper<EnterpriseApply>()
                .eq(EnterpriseApply::getLegalPersonPhone, enterpriseApply.getLegalPersonPhone())
                .eq(EnterpriseApply::getStatus, 1));
        if (phoneCount > 0) {
            throw new ServiceException("该手机号已经提交过申请");
        }
        enterpriseApplyMapper.insert(enterpriseApply);
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        systemMessageMqDto.setMessageDetail("企业申请通知-有新的" + enterpriseApply.getEnterpriseName() + "企业申请入驻平台啦，请注意查看");
        systemMessageMqDto.setMessageTitle("企业申请");
        systemMessageMqDto.setMessageType(2);
        systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
            {
                add(0L);
            }
        });
        userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO("企业入驻申请成功", enterpriseApply.getId());
    }

    @Autowired
    private IEvaluationApiFeign evaluationApiFeign;

    @Override
    public ReturnVO<JgPageVo<EnterpriseApply>> listEnterpriseApply(EnterpriseApplyDto enterpriseApplyDto) {
        PageHelper.startPage(enterpriseApplyDto.getCurPage(), enterpriseApplyDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.isNotBlank(enterpriseApplyDto.getEnterpriseName())) {
            queryWrapper.like("enterprise_name", enterpriseApplyDto.getEnterpriseName());
        }
        if (StringUtils.isNotBlank(enterpriseApplyDto.getLegalPersonPhone())) {
            queryWrapper.eq("legal_person_phone", enterpriseApplyDto.getLegalPersonPhone());
        }
        List<EnterpriseApply> enterpriseApplies = enterpriseApplyMapper.selectList(queryWrapper);
        //查询行业类目id
        for (EnterpriseApply enterpriseApply : enterpriseApplies) {
            if (enterpriseApply.getBusinessCategoryId() != null) {
                ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(enterpriseApply.getBusinessCategoryId());
                if ("200".equals(stringReturnVO.getCode())) {
                    enterpriseApply.setCategoryName(stringReturnVO.getData());
                }
            }
        }
        return new ReturnVO("企业入驻申请成功", new JgPageVo<>(new PageInfo(enterpriseApplies)));
    }

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Transactional
    @Override
    public ReturnVO<Long> passEnterpriseApply(AdminUser adminUser, PassEnterpriseApplyDto passEnterpriseApplyDto) {
        EnterpriseApply enterpriseApply = enterpriseApplyMapper.selectById(passEnterpriseApplyDto.getEnterpriseApplyId());
        if (enterpriseApply == null) {
            throw new ServiceException("该id对应企业申请不存在");
        }
        if (enterpriseApply.getStatus() != 0) {
            throw new ServiceException("该申请已经被审核");
        }
        //将申请列表的数据填充到企业里
        EnterpriseInsDto enterpriseInsDto = new EnterpriseInsDto();
        BeanUtils.copyProperties(enterpriseApply, enterpriseInsDto);
        enterpriseInsDto.setId(null);
        enterpriseInsDto.setPassword(passEnterpriseApplyDto.getPassword());
        enterpriseInsDto.setUsername(passEnterpriseApplyDto.getUsername());
        //总后台新增企业
        ReturnVO<Long> returnVO = enterpriseService.saveEnterprise(enterpriseInsDto);
        //设置申请人的企业
        if ("200".equals(returnVO.getCode())) {
            WxUser wxUser = wxUserMapper.selectById(enterpriseApply.getWxUserId());
            if (wxUser != null) {
                wxUser.setEnterpriseId(returnVO.getData());
                if (StringUtils.isNotBlank(wxUser.getToken())) {
                    if (redisTemplate.hasKey(wxUser.getToken())) {
                        //删除废弃token
                        redisTemplate.delete(wxUser.getToken());
                    }
                }
                //存放新的token
                String token = RedisConstants.WX_TOKEN + UUID.randomUUID().toString();
                wxUser.setToken(token);
                redisTemplate.opsForValue().set(token, JSONObject.toJSONString(wxUser), 60 * 60 * 24 * 10 * 30, TimeUnit.SECONDS);
                wxUserMapper.updateById(wxUser);
                //设置为默认院长
                Long enterpriseId = returnVO.getData();
                Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
                enterprise.setWxUserId(wxUser.getId());
                enterpriseMapper.updateById(enterprise);
            }
        }
        //企业关联企业申请数据
        Long data = returnVO.getData();
        enterpriseApply.setEnterpriseId(data);
        //审核通过
        enterpriseApply.setStatus(1);
        enterpriseApply.setCheckName(adminUser.getUsername());
        enterpriseApply.setCheckPhone(adminUser.getPhone());
        enterpriseApplyMapper.updateById(enterpriseApply);
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        //发送短信
        if (passEnterpriseApplyDto.getIsSms() != null && passEnterpriseApplyDto.getIsSms() == 1) {
            systemMessageMqDto.setPhones(
                    new ArrayList<String>() {
                        {
                            add(enterpriseApply.getLegalPersonPhone());
                        }
                    }
            );
            systemMessageMqDto.setTemplateId(SmsConfig.enterpriseCheckPassId);
            systemMessageMqDto.setParams(new ArrayList<String>() {
                {
                    add(enterpriseApply.getEnterpriseName());
                    add(LocalDate.now().toString());
                    add(passEnterpriseApplyDto.getUsername());
                    add(passEnterpriseApplyDto.getPassword());
                    add(passEnterpriseApplyDto.getRemark());
                }
            });
        }
        systemMessageMqDto.setMessageDetail("恭喜您，您在五星智造平台申请的" + enterpriseApply.getEnterpriseName() + "企业在" + LocalDate.now().toString() + "时，已审核通过。账号为" + passEnterpriseApplyDto.getUsername() + "，默认密码为" + passEnterpriseApplyDto.getPassword() + "，备注" + passEnterpriseApplyDto.getRemark() + "，请您在登录后及时更换密码");
        systemMessageMqDto.setMessageTitle("企业审核通过");
        systemMessageMqDto.setWxUserIds(
                new ArrayList<Long>() {
                    {
                        add(enterpriseApply.getWxUserId());
                    }
                }
        );
        userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        //审核通过发布消息
        SystemMessageMqDto enterpriseSystemMessageMqDto = new SystemMessageMqDto();
        enterpriseSystemMessageMqDto.setMessageDetail("恭喜您成功入驻五星智造APP学习平台!");
        enterpriseSystemMessageMqDto.setMessageTitle("系统审核通过");
        enterpriseSystemMessageMqDto.setMessageType(1);
        enterpriseSystemMessageMqDto.setWxUserIds(
                new ArrayList<Long>() {
                    {
                        add(enterpriseApply.getEnterpriseId());
                    }
                }
        );
        userMessageProducer.ackMQSender(JSONObject.toJSONString(enterpriseSystemMessageMqDto));
        return new ReturnVO("企业申请通过成功", data);
    }

    @Autowired
    private UserMessageProducer userMessageProducer;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Override
    public ReturnVO failEnterpriseApply(AdminUser adminUser, FailEnterpriseApplyDto failEnterpriseApplyDto) {
        EnterpriseApply enterpriseApply = enterpriseApplyMapper.selectById(failEnterpriseApplyDto.getEnterpriseApplyId());
        if (enterpriseApply == null) {
            throw new ServiceException("该id对应企业申请不存在");
        }
        if (enterpriseApply.getStatus() != 0) {
            throw new ServiceException("该申请已经被审核");
        }
        //审核失败
        enterpriseApply.setStatus(2);
        enterpriseApply.setReturnRemark(failEnterpriseApplyDto.getReturnRemark());
        enterpriseApply.setCheckName(adminUser.getUsername());
        enterpriseApply.setCheckPhone(adminUser.getPhone());
        enterpriseApply.setIsSms(failEnterpriseApplyDto.getIsSms());
        enterpriseApply.setIsPublic(failEnterpriseApplyDto.getIsPublic());
        enterpriseApplyMapper.updateById(enterpriseApply);
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        //发送短信
        if (failEnterpriseApplyDto.getIsSms() != null && failEnterpriseApplyDto.getIsSms() == 1) {
            systemMessageMqDto.setPhones(new ArrayList<String>() {
                {
                    add(enterpriseApply.getLegalPersonPhone());
                }
            });
            systemMessageMqDto.setTemplateId(SmsConfig.enterpriseCheckFailId);
            systemMessageMqDto.setParams(new ArrayList<String>() {
                {
                    add(enterpriseApply.getEnterpriseName());
                    add(LocalDate.now().toString());
                }
            });
        }
        systemMessageMqDto.setMessageDetail(failEnterpriseApplyDto.getReturnRemark());
        systemMessageMqDto.setMessageTitle("企业审核未通过");
        systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
            {
                add(enterpriseApply.getWxUserId());
            }
        });
        userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO("企业申请驳回成功", enterpriseApply.getId());
    }

    @Override
    public ReturnVO selectStatus(Long wxUserId) {
        List<EnterpriseApply> enterpriseApplies = enterpriseApplyMapper.selectList(new LambdaQueryWrapper<EnterpriseApply>()
                .eq(EnterpriseApply::getWxUserId, wxUserId)
                .orderByDesc(EnterpriseApply::getCreateTime));
        if (enterpriseApplies.size() != 0) {
            return new ReturnVO("企业申请状态", enterpriseApplies.get(0).getStatus());
        }
        return new ReturnVO("企业申请状态", null);
    }


}
